package com.pomr.util.common;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.chainsaw.Main;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWTSigner;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.internal.com.fasterxml.jackson.databind.ObjectMapper;
import com.pomr.model.sys.Role;
import com.pomr.model.sys.User;

public class JWT {
	private static final String SECRET = "XX#$%()(#*!()!KL<><MQLMNQNQJQK sdfkjsdrow32234545fdf>?N<:{LWPW";

    private static final String EXP = "exp";

    private static final String PAYLOAD = "payload";

    //加密，传入一个对象和有效期
    public static <T> String sign(T object, long maxAge) {
        try {
            final JWTSigner signer = new JWTSigner(SECRET);
            final Map<String, Object> claims = new HashMap<String, Object>();
//            ObjectMapper mapper = new ObjectMapper();
//            String jsonString = mapper.writeValueAsString(object);
            String jsonString = JSONObject.toJSONString(object);
            claims.put(PAYLOAD, jsonString);
            claims.put(EXP, System.currentTimeMillis() + maxAge);
            return signer.sign(claims);
        } catch(Exception e) {
        	e.printStackTrace();
            return null;
        }
    }

    //解密，传入一个加密后的token字符串和解密后的类型
    public static<T> T unsign(String jwt, Class<T> classT) {
        final JWTVerifier verifier = new JWTVerifier(SECRET);
        try {
            final Map<String,Object> claims= verifier.verify(jwt);
            if (claims.containsKey(EXP) && claims.containsKey(PAYLOAD)) {
                long exp = (Long)claims.get(EXP);
                long currentTimeMillis = System.currentTimeMillis();
                if (exp > currentTimeMillis) {
                    String json = (String)claims.get(PAYLOAD);
//                    ObjectMapper objectMapper = new ObjectMapper();
//                    return objectMapper.readValue(json, classT);
                    return JSONObject.parseObject(json, classT);
                }
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }
    
    /**
     * 获取token中的user
     * @param request
     * @return
     */
    public static User findUserByToken(HttpServletRequest request){
    	String h = request.getHeader("Authorization");
    	if(h==null || h.trim().equals("")){
    		return null;
    	}
    	String token = request.getHeader("Authorization").substring(7).split("-&-")[1];
    	System.out.println(token);
		User user = unsign(token, User.class);
		return user;
    }
    
    public static void main(String[] args) {
		User user = new User();
		user.setId(1);
		user.setName("123");
		Role r = new Role();
		r.setId(1);
		user.setRole(r);
		String aa = sign(user,180000000);
		System.out.println(aa);
		System.out.println(unsign(aa,User.class));
    }
}
